//
//  VIPTools.swift
//  TsWindow
//
//  Created by Taurin on 12/2/20.
//

import Cocoa
import EventKit

class VIPTools: NSObject {
    fileprivate let eventStore = EKEventStore()    // 建议使用单利模式
    fileprivate  var isAuthor = false     // 检测是否进行授权
   
}
/*
extension VIPTools {
    // 播放文字
    static func speaking(_ text: String) {
        let speach = NSSpeechSynthesizer()
        speach.startSpeaking(text)
    }
    
    // 设置朗读声音
    func speach_setVoice() {
        for voiceName in NSSpeechSynthesizer.availableVoices {
            print(voiceName)
            // VoiceName(_rawValue: com.apple.speech.synthesis.voice.Alex)
        }
        
        let speach = NSSpeechSynthesizer()
        let result = speach.setVoice(NSSpeechSynthesizer.VoiceName.init(rawValue: "com.apple.speech.synthesis.voice.damayanti"))
        if result {
            print("success")
        }else{
            print("failure")
        }
    }
}

// 系统提醒
// EKEventStore 与EKReminder
extension VIPTools{
    fileprivate func remindme(){
        // 获取系统的授权状态
        let authorStatus = EKEventStore.authorizationStatus(for: EKEntityType.reminder)
       // 判断授权结果
        switch authorStatus {
        case .authorized:   // 已授权,设置授权结果为true
            isAuthor = true
        case .notDetermined:   // 尚未授权,进行授权请求(回调在子线程,若处理UI,需要切到主线程)
            eventStore.requestAccess(to: .reminder, completion: { [weak self] (granted, error) in
                guard let strongSelf = self else {return}
                if granted {
                    DispatchQueue.main.async {
                        strongSelf.isAuthor = granted
                        strongSelf.createRemind()
                    }
                }
            })
        case .denied,.restricted:  // 用户拒绝授权
            print("user deny ")
        }
        
        if !isAuthor {return}
        createRemind()
    }
    
    // 创建提醒
    fileprivate func createRemind(){
       
        let reminder = EKReminder(eventStore: eventStore)   // 创建提醒器
        reminder.calendar = eventStore.defaultCalendarForNewReminders() // 设置新提醒
        reminder.title = "remide title"      // 设置提醒事件的标题
        let alarmDate = Date(timeInterval: 15, since: Date())   // 设置提醒时间:本例为15秒后
        let alarm = EKAlarm(absoluteDate: alarmDate)    // 创建提醒
        reminder.addAlarm(alarm)          // 添加提醒到提醒器中
        do {
            try  eventStore.save(reminder, commit: true)       // 添加事件到系统提醒应用
        } catch  {
            print("save failure: \(error.localizedDescription)")
        }
    }
}


//let kSelectedFilePath = "userSelectedPath"
//extension VIPTools {
//    @IBOutlet weak var repoPath: NSTextField!           // git 仓库path
//    @IBOutlet weak var savePath: NSTextField!           // 本地保存路径
//    @IBOutlet var showInfoTextView: NSTextView!     // 显示结果内容
//
//    var isLoadingRepo  = false                                 // 记录是否正在加载中..
//
//    var outputPipe = Pipe()
//
//    var task : Process?
//
//    override func viewDidLoad() {
//        super.viewDidLoad()
//        showInfoTextView.textColor = NSColor.white
//        // Do any additional setup after loading the view.
//    }
//
//// 选择保存路径
//    @IBAction func selectPath(_ sender: NSButton) {
//        // 1. 创建打开文档面板对象
//        let openPanel = NSOpenPanel()
//        // 2. 设置确认按钮文字
//        openPanel.prompt = "Select"
//        // 3. 设置禁止选择文件
//        openPanel.canChooseFiles = true
//        // 4. 设置可以选择目录
//        openPanel.canChooseDirectories = true
//        // 5. 弹出面板框
//        openPanel.beginSheetModal(for: self.view.window!) { (result) in
//            // 6. 选择确认按钮
//            if result == NSModalResponseOK {
//                // 7. 获取选择的路径
//                self.savePath.stringValue = (openPanel.directoryURL?.path)!
//                // 8. 保存用户选择路径(为了可以在其他地方有权限访问这个路径,需要对用户选择的路径进行保存)
//                UserDefaults.standard.setValue(openPanel.url?.path, forKey: kSelectedFilePath)
//                UserDefaults.standard.synchronize()
//            }
//            // 9. 恢复按钮状态
//            sender.state = NSOffState
//        }
//    }
//    // clone按钮事件:(这里名称用了pull,不想改了,大家自己使用的时候,最好使用clone来命名)
//    @IBAction func startPull(_ sender: NSButton) {
//        guard  let executePath = UserDefaults.standard.value(forKey: kSelectedFilePath) as? String else {
//            print("no selected path")
//            return
//        }
//        guard repoPath.stringValue != "" else {return}
//        if isLoadingRepo {return}   // 如果正在执行,则返回
//        isLoadingRepo = true   // 设置正在执行标记
//        task = Process()     // 创建NSTask对象
//        // 设置task
//        task?.launchPath = "/bin/bash"    // 执行路径(这里是需要执行命令的绝对路径)
//        // 设置执行的具体命令
//        task?.arguments = ["-c","cd \(executePath); git clone \(repoPath.stringValue)"]
//
//        task?.terminationHandler = { proce in              // 执行结束的闭包(回调)
//            self.isLoadingRepo = false    // 恢复执行标记
//            print("finished")
//            self.showFiles()
//        }
//        captureStandardOutputAndRouteToTextView(task!)
//        task?.launch()                // 开启执行
//        task?.waitUntilExit()       // 阻塞直到执行完毕
//    }
//
//    // 显示目录文档列表
//    fileprivate func showFiles() {
//        guard  let executePath = UserDefaults.standard.value(forKey: kSelectedFilePath) as? String else {
//            print("no selected path")
//            return
//        }
//       let listTask = Process()     // 创建NSTask对象
//        // 设置task
//        listTask.launchPath = "/bin/bash"    // 执行路径(这里是需要执行命令的绝对路径)
//        // 设置执行的具体命令
//
//        listTask.arguments = ["-c","cd \(executePath + "/" + (repoPath.stringValue as NSString).lastPathComponent); ls "]
//
//        captureStandardOutputAndRouteToTextView(listTask)
//
//        listTask.launch()                // 开启执行
//        listTask.waitUntilExit()
//
//    }
//
//}

//extension VIPTools{
//    fileprivate func captureStandardOutputAndRouteToTextView(_ task:Process) {
//        //1. 设置标准输出管道
//        outputPipe = Pipe()
//        task.standardOutput = outputPipe
//
//        //2. 在后台线程等待数据和通知
//        outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotify()
//
//        //3. 接受到通知消息
//        NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outputPipe.fileHandleForReading , queue: nil) { notification in
//
//            //4. 获取管道数据 转为字符串
//            let output = self.outputPipe.fileHandleForReading.availableData
//            let outputString = String(data: output, encoding: String.Encoding.utf8) ?? ""
//            if outputString != ""{
//                //5. 在主线程处理UI
//                DispatchQueue.main.async(execute: {
//                    let previousOutput = self.showInfoTextView.string ?? ""
//                    let nextOutput = previousOutput + "\n" + outputString
//                    self.showInfoTextView.string = nextOutput
//                    // 滚动到可视位置
//                    let range = NSRange(location:nextOutput.characters.count,length:0)
//                    self.showInfoTextView.scrollRangeToVisible(range)
//                })
//            }
//            //6. 继续等待新数据和通知
//            self.outputPipe.fileHandleForReading.waitForDataInBackgroundAndNotify()
//        }
//    }
//
//}
//
//extension ViewController {
//    public struct Lggs: OptionSet {
//        public var rawValue: UInt
//
//        public static var en: ViewController.Lggs { return ViewController.Lggs(rawValue: 1)  }
// 
//        public static var ch: ViewController.Lggs { return ViewController.Lggs(rawValue: 2)  }
//
//        public static var ja: ViewController.Lggs { return ViewController.Lggs(rawValue: 4)  }
//
//        public static var al: ViewController.Lggs { return ViewController.Lggs(rawValue: 8)  }
//
//        public static var tu: ViewController.Lggs { return ViewController.Lggs(rawValue: 16) }
//
//        public static var he: ViewController.Lggs { return ViewController.Lggs(rawValue: 32) }
//    }
//}
*/
//
////  SuperViewController.swift
////  TsWindow
////
////  Created by Taurin on 11/30/20.
////
//
//import Cocoa
//
//class SuperViewController: VIPViewController {
//    
//    // ****** 注意去掉沙盒
//    lazy var task : Process = {
//        let obj = Process()
//        return obj
//    }()
//    
//    var outputPipe:Pipe?
//    
//    lazy var txtView: NSTextView = {
//        let view = NSTextView()
//        view.string = "\n"
//        view.backgroundColor = NSColor.clear
//        view.textColor = NSColor.white
//        return view
//    }()
//    
//    lazy var scrollView: NSScrollView = {
//        let view = NSScrollView()
//        view.borderType = .noBorder
//        view.hasVerticalScroller = true
//        view.hasHorizontalScroller = false
//        view.documentView = txtView
//        return view
//    }()
//    
//    lazy var button: NSButton = {
//        let view = NSButton()
//        view.target = self
//        view.wantsLayer = true
//        view.layer?.backgroundColor = NSColor.red.cgColor
//        view.action = #selector(self.didTapButton(sender:))
//        return view
//    }()
//    
//    deinit {
//        print(window?.windowController)
//    }
//    
//    override func viewDidLoad() {
//        super.viewDidLoad()
//        let wc = window?.windowController
//        print(wc)
//        view.addSubview(button)
//        button.frame = CGRect.init(x: 0, y: 0, width: 100, height: 100)
//        
//        view.addSubview(scrollView)
//        
//        scrollView.snp.makeConstraints { (make) in
//            make.left.equalTo(150)
//            make.bottom.equalTo(50)
//            make.width.equalTo(500)
//            make.height.equalTo(800)
//        }
//        
//        // scrollView.frame = CGRect.init(x: 150, y:50, width: 500, height: 800)
//     
//        
//        
//        view.layoutSubtreeIfNeeded()
//        txtView.frame = scrollView.frame
////        txtView.snp.makeConstraints { (make) in
////            make.left.equalTo(150)
////            make.bottom.equalTo(50)
////            make.width.equalTo(500)
////            make.height.equalTo(800)
////        }
//    }
//    
////    @objc func didTapButton(sender: NSButton) {
////        task.launchPath = "/bin/bash"
////        task.arguments = ["-c","cd /Users/vipcode/Desktop/VIPCODE; pod repo update;"]
//////        task.terminationHandler
////        task.terminationHandler = { proce in
////            //            self.isLoadingRepo = false
////            print("finished")
////            //            self.showFiles()
////
////        }
////        captureStandardOutputAndRouteToTextView(task)
////        task.launch()
////        task.waitUntilExit()
////    }
//    
////    func cmd(arguments: [String]) -> String {
////        let task = Process()
////        let pipe = Pipe()
////        task.launchPath = "/bin/bash"
////        let firstObj = "-c"
////        var arg: [String] = arguments
////        if !arguments.contains(firstObj) {
////            arg.insert(firstObj, at: 0)
////        }
////        task.arguments = arg
////        task.standardOutput = pipe
////        let file = pipe.fileHandleForReading
////        task.launch()
////
////        let data = file.readDataToEndOfFile()
////        let result = String(bytes: data, encoding: String.Encoding.utf8) ?? ""
////        return result
////    }
//    
//    
//    @objc func didTapButton(sender: NSButton) {
//        task.launchPath = "/bin/bash"
//        task.arguments = ["-c","pod repo update;"]
////        task.terminationHandler
//        task.terminationHandler = { proce in
//            //            self.isLoadingRepo = false
//            print("finished")
//            //            self.showFiles()
//
//        }
//        captureStandardOutputAndRouteToTextView(task)
//        task.launch()
//        task.waitUntilExit()
//    }
//    
//    
//    //    @objc func didTapButton(sender: NSButton) {
//    
//    //        let subvc = SubViewController()
//    //        presentAsSheet(subvc)
//    //        present(subvc, animator: NSViewControllerPresentationAnimator)
//    //    }
//}
//
//
//extension SuperViewController {
//    fileprivate func captureStandardOutputAndRouteToTextView(_ task:Process) {
//        //1. 设置标准输出管道
//        outputPipe = Pipe()
//        task.standardOutput = outputPipe
//        
//        //2. 在后台线程等待数据和通知
//        outputPipe?.fileHandleForReading.waitForDataInBackgroundAndNotify()
//        
//        //3. 接受到通知消息
//        NotificationCenter.default.addObserver(forName: NSNotification.Name.NSFileHandleDataAvailable, object: outputPipe?.fileHandleForReading , queue: nil) { notification in
//            
//            //4. 获取管道数据 转为字符串
//            guard let output = self.outputPipe?.fileHandleForReading.availableData else { return }
//            
//            let outputString = String(data: output, encoding: String.Encoding.utf8) ?? ""
//            print(outputString)
//            if outputString != ""{
//                //5. 在主线程处理UI
//                DispatchQueue.main.async(execute: {
//                    let previousOutput = self.txtView.string
//                    let nextOutput = previousOutput + "\n" + outputString
//                    self.txtView.string = nextOutput
//                    // 滚动到可视位置
//                    let range = NSRange(location:nextOutput.count,length:0)
//                    self.txtView.scrollRangeToVisible(range)
//                    print("outputString: " + outputString)
//                })
//            }
//            //6. 继续等待新数据和通知
//            self.outputPipe?.fileHandleForReading.waitForDataInBackgroundAndNotify()
//        }
//    }
//}
